<template>
  <div class="notifications-page">
    <div class="page-header">
      <h1>通知中心</h1>
      <div class="header-actions">
        <el-button 
          v-if="notificationStore.unreadCount > 0"
          type="primary" 
          @click="markAllAsRead"
          :loading="markingAllRead"
        >
          全部已读
        </el-button>
      </div>
    </div>

    <!-- 统计信息 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ notificationStore.unreadCount }}</div>
              <div class="stat-label">未读通知</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ totalNotifications }}</div>
              <div class="stat-label">全部通知</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ readNotifications }}</div>
              <div class="stat-label">已读通知</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 筛选器 -->
    <div class="filter-section">
      <el-card>
        <div class="filter-controls">
          <el-select 
            v-model="filterStatus" 
            placeholder="状态筛选" 
            style="width: 150px; margin-right: 20px;"
            @change="handleFilterChange"
          >
            <el-option label="全部" value="all" />
            <el-option label="未读" value="UNREAD" />
            <el-option label="已读" value="READ" />
          </el-select>
          
          <el-select 
            v-model="filterType" 
            placeholder="类型筛选" 
            style="width: 180px; margin-right: 20px;"
            @change="handleFilterChange"
          >
            <el-option label="全部类型" value="all" />
            <el-option label="头像审核通过" value="AVATAR_APPROVED" />
            <el-option label="头像审核拒绝" value="AVATAR_REJECTED" />
            <el-option label="系统通知" value="SYSTEM_NOTICE" />
            <el-option label="安全提醒" value="SECURITY_ALERT" />
          </el-select>

          <el-button @click="refreshNotifications" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 通知列表 -->
    <div class="notifications-list">
      <el-card>
        <div v-loading="loading">
          <div v-if="filteredNotifications.length === 0" class="empty-state">
            <el-empty description="暂无通知" />
          </div>
          
          <div v-else>
            <div 
              v-for="notification in filteredNotifications"
              :key="notification.id"
              class="notification-item"
              :class="{ 'unread': notification.status === 'UNREAD' }"
              @click="handleNotificationClick(notification)"
            >
              <div class="notification-icon">
                <el-icon :size="24" :color="getIconColor(notification.type)">
                  <component :is="getIconComponent(notification.type)" />
                </el-icon>
              </div>
              
              <div class="notification-content">
                <div class="notification-header">
                  <h3 class="notification-title">{{ notification.title }}</h3>
                  <div class="notification-meta">
                    <el-tag 
                      :type="getStatusTagType(notification.status)" 
                      size="small"
                    >
                      {{ getStatusText(notification.status) }}
                    </el-tag>
                    <span class="notification-time">
                      {{ formatTime(notification.createdAt) }}
                    </span>
                  </div>
                </div>
                
                <p class="notification-text">{{ notification.content }}</p>
                
                <div v-if="notification.readAt" class="read-info">
                  已读于 {{ formatTime(notification.readAt) }}
                </div>
              </div>
              
              <div class="notification-actions">
                <el-button 
                  v-if="notification.status === 'UNREAD'"
                  size="small"
                  @click.stop="markAsRead(notification.id)"
                >
                  标为已读
                </el-button>
                
                <el-button 
                  size="small"
                  type="primary"
                  link
                  @click.stop="viewNotificationDetail(notification)"
                >
                  查看详情
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div v-if="totalPages > 1" class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50]"
            :total="totalNotifications"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Refresh,
  SuccessFilled,
  WarningFilled, 
  InfoFilled,
  CircleCloseFilled
} from '@element-plus/icons-vue'
import { useNotificationStore } from '../stores/notification'
import { formatDistanceToNow } from 'date-fns'
import { zhCN } from 'date-fns/locale'

const router = useRouter()
const notificationStore = useNotificationStore()

// 响应式数据
const loading = ref(false)
const markingAllRead = ref(false)
const currentPage = ref(1)
const pageSize = ref(20)
const filterStatus = ref('all')
const filterType = ref('all')

// 计算属性
const totalNotifications = computed(() => notificationStore.notifications.length)
const readNotifications = computed(() => 
  notificationStore.notifications.filter(n => n.status === 'READ').length
)
const totalPages = computed(() => Math.ceil(totalNotifications.value / pageSize.value))

const filteredNotifications = computed(() => {
  let notifications = [...notificationStore.notifications]
  
  // 状态筛选
  if (filterStatus.value !== 'all') {
    notifications = notifications.filter(n => n.status === filterStatus.value)
  }
  
  // 类型筛选
  if (filterType.value !== 'all') {
    notifications = notifications.filter(n => n.type === filterType.value)
  }
  
  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return notifications.slice(start, end)
})

// 方法
const refreshNotifications = async () => {
  loading.value = true
  try {
    await notificationStore.fetchNotifications(0, 1000) // 获取大量通知
    await notificationStore.fetchNotificationStats()
  } catch (error) {
    ElMessage.error('刷新通知失败')
  } finally {
    loading.value = false
  }
}

const markAllAsRead = async () => {
  try {
    await ElMessageBox.confirm('确定要标记所有通知为已读吗？', '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    markingAllRead.value = true
    const result = await notificationStore.markAllNotificationsAsRead()
    if (result.success) {
      ElMessage.success('所有通知已标记为已读')
      await refreshNotifications()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  } finally {
    markingAllRead.value = false
  }
}

const markAsRead = async (notificationId) => {
  const result = await notificationStore.markNotificationAsRead(notificationId)
  if (result.success) {
    ElMessage.success('已标记为已读')
  }
}

const handleNotificationClick = async (notification) => {
  // 如果是未读状态，先标记为已读
  if (notification.status === 'UNREAD') {
    await markAsRead(notification.id)
  }
  
  // 跳转到通知详情页
  router.push(`/notifications/${notification.id}`)
}

const navigateToRelated = (notification) => {
  switch (notification.type) {
    case 'AVATAR_APPROVED':
    case 'AVATAR_REJECTED':
      router.push('/profile?tab=avatar')
      break
    case 'SYSTEM_NOTICE':
    case 'SECURITY_ALERT':
    default:
      // 可以添加更多页面导航逻辑
      break
  }
}

const viewNotificationDetail = (notification) => {
  // 直接跳转到通知详情页，不自动标记为已读
  router.push(`/notifications/${notification.id}`)
}

const handleFilterChange = () => {
  currentPage.value = 1 // 重置页码
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
}

// 工具函数
const getIconComponent = (type) => {
  const iconMap = {
    'AVATAR_APPROVED': SuccessFilled,
    'AVATAR_REJECTED': WarningFilled,
    'SYSTEM_NOTICE': InfoFilled,
    'SECURITY_ALERT': CircleCloseFilled
  }
  return iconMap[type] || InfoFilled
}

const getIconColor = (type) => {
  const colorMap = {
    'AVATAR_APPROVED': '#67C23A',
    'AVATAR_REJECTED': '#E6A23C',
    'SYSTEM_NOTICE': '#409EFF',
    'SECURITY_ALERT': '#F56C6C'
  }
  return colorMap[type] || '#409EFF'
}

const getStatusTagType = (status) => {
  return status === 'UNREAD' ? 'danger' : 'info'
}

const getStatusText = (status) => {
  return status === 'UNREAD' ? '未读' : '已读'
}

const formatTime = (timeString) => {
  if (!timeString) return ''
  try {
    const date = new Date(timeString)
    return formatDistanceToNow(date, { 
      addSuffix: true, 
      locale: zhCN 
    })
  } catch (error) {
    return timeString
  }
}

// 生命周期
onMounted(() => {
  refreshNotifications()
})

// 监听store变化
watch(() => notificationStore.notifications, () => {
  // 当store中的通知发生变化时，可以进行一些操作
}, { deep: true })
</script>

<style scoped>
.notifications-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  color: var(--el-text-color-primary);
}

.stats-section {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
}

.stat-content {
  padding: 10px;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: var(--el-color-primary);
  margin-bottom: 5px;
}

.stat-label {
  color: var(--el-text-color-regular);
  font-size: 14px;
}

.filter-section {
  margin-bottom: 20px;
}

.filter-controls {
  display: flex;
  align-items: center;
}

.notification-item {
  display: flex;
  align-items: flex-start;
  padding: 16px;
  border-bottom: 1px solid var(--el-border-color-light);
  cursor: pointer;
  transition: background-color 0.2s;
}

.notification-item:hover {
  background-color: var(--el-bg-color-page);
}

.notification-item.unread {
  background-color: var(--el-color-primary-light-9);
  border-left: 3px solid var(--el-color-primary);
}

.notification-item:last-child {
  border-bottom: none;
}

.notification-icon {
  margin-right: 16px;
  margin-top: 4px;
}

.notification-content {
  flex: 1;
  min-width: 0;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
}

.notification-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.notification-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-shrink: 0;
}

.notification-time {
  color: var(--el-text-color-secondary);
  font-size: 12px;
}

.notification-text {
  margin: 0 0 8px 0;
  color: var(--el-text-color-regular);
  line-height: 1.5;
}

.read-info {
  font-size: 12px;
  color: var(--el-text-color-placeholder);
}

.notification-actions {
  margin-left: 16px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.empty-state {
  text-align: center;
  padding: 40px;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
